<template>
	<a-modal :centered="true" open title="摄像头权限" width="660px" @cancel="CloseModal">
		<div class="content">
			<a-spin :spinning="pageLoading">
				<div class="account-data-permissions">
					<!-- 选择通道卡片 -->
					<a-card class="cards-item-left" :body-style="{ overflowY: 'scroll' }">
						<template #title>
							<span class="card-title font-14-bold">设备列表</span>
						</template>

						<a-input
							v-model:value.trim="searchValue"
							class="cards-input-search"
							style="width: 280px"
							placeholder="关键词"
							@press-enter="SearchTreeByInput(treeState)"
						>
							<template #prefix>
								<span class="iconfont icon-search-line" @click="SearchTreeByInput(treeState)"></span>
							</template>
						</a-input>
						<a-tree
							v-model:expandedKeys="treeState.expandedKeys"
							v-model:selectedKeys="treeState.selectedKeys"
							v-model:checkedKeys="treeState.checkedKeys"
							class="left-tree"
							:auto-expand-parent="treeState.autoExpandParent"
							:field-names="{ children: 'children', title: 'name', key: 'id' }"
							:tree-data="treeState.treeData"
							:checkable="treeState.isshowchecked ? false : true"
							@check="CheckTreeNode"
						>
							<template #title="{ data, level }">
								<div class="tree-node-item">
									<!-- <span
									v-if="Number(data.key) !== 0 && level === 2"
									class="iconfont icon-Monitoring-full"
									style="margin-right: 8px; font-size: 14px"
								></span> -->
									<span v-if="data.name.indexOf(searchValue) > -1">
										{{ data.name.substr(0, data.name.indexOf(searchValue)) }}
										<span class="font-14-bold">{{ searchValue }}</span>
										{{ data.name.substr(data.name.indexOf(searchValue) + searchValue.length) }}
									</span>
									<span v-else>{{ data.name }}</span>
								</div>
							</template>
						</a-tree>
					</a-card>
					<!-- 右侧卡片-->
					<a-card size="small" class="cards-item-right" style="height: 430px" :body-style="{ overflowY: 'scroll' }">
						<template #title>
							<span class="card-title">已选</span>
							<span style="font-weight: 400; color: #fff">{{ rightState.selectedList.length }}</span>
						</template>
						<div style="margin-top: 10px">
							<div :key="item.id" v-for="(item, index) in rightState.selectedList" class="select-item">
								<div style="width: 90%" class="select-text">{{ item.name }}</div>
								<div class="select-del" @click="SingleDelete(index, item)">
									<span class="iconfont icon-close-circle-fill" style="cursor: pointer" @click="SearchTreeByInput(treeState)"></span>
									<!-- <span class="iconfont icon-DeleteOutlined" style="cursor: pointer"></span> -->
								</div>
							</div>
						</div>
						<template #extra><span class="empty ant-btn-link" style="cursor: pointer" @click="BatchDelete(treeState)">清空</span></template>
					</a-card>
				</div>
			</a-spin>
		</div>
		<template #footer>
			<a-button size="small" class="btn-default" @click="CloseModal">取消</a-button>

			<a-button size="small" type="primary" :loading="confirmLoading" :disabled="pageLoading" @click="FormSave">确定</a-button>
		</template>
	</a-modal>
</template>

<script setup lang="ts" name="CameraDataPermissions">
import type { TreeProps } from 'ant-design-vue';
import { AccountAPI, AlgorithmConfigurationAPI } from '../../../api';
import type { TsTreeState, TsRightList } from './type';
import { findSelectedNodes } from '../../../utils';
import type { TsAccountModalType } from '../../../type';
const props = withDefaults(defineProps<{ userId: string | number; type: TsAccountModalType }>(), {
	userId: '',
	type: 'cameraDataAuth'
});
const emits = defineEmits<{
	(e: 'ok', flag: 'cameraDataAuth'): void;
	(e: 'update:type', value: ''): void;
	(e: 'update:saveData', value: any): void;
}>();
const pageLoading = ref(false);
/*
1.新增 修改接口 deviceIdList =  treeState.checkedKeys

2.回显 只需要 把 formatRightSelectData(treeState.checkedKeys) 函数执行一次

3. 注意报错hooks 返回void 的类型定义

 */
const $message: any = inject('$message');

const dataId = ref();
const CloseModal = (): void => {
	emits('update:saveData', '');
	emits('update:type', '');
};
interface TsSelectedList {
	id: string;
	name: string;
	children?: TsSelectedList[];
}
const confirmLoading = ref<boolean>(false);
// 树状态
const treeState = reactive<TsTreeState>({
	expandedKeys: [],
	selectedKeys: [],
	checkedKeys: [],
	treeData: [],
	flatTreeObj: {},
	autoExpandParent: false,
	isshowchecked: true
});

// 右侧列表状态
const rightState = reactive<TsRightList<TsSelectedList[]>>({
	selectedList: [],
	selectedKeys: []
});

const FormSave = async (): Promise<void> => {
	// 保存
	let updateDate = {
		id: dataId.value,
		personId: props.userId,
		dataType: 0,
		deviceIdList: treeState.checkedKeys.filter((item) => item !== '0')
	};
	confirmLoading.value = true;
	let res: TsRes = await AccountAPI.UpdatePermissionData(JSON.parse(JSON.stringify(updateDate)));
	confirmLoading.value = false;
	if (res && res.code === 0) {
		$message.success('保存数据权限成功');
		CloseModal();
		emits('ok', 'cameraDataAuth');
	}
};

// 格式化右侧 keys ===> treeState.checkedKeys
const formatRightSelectData = (keys: Array<string | number>): void => {
	rightState.selectedList = findSelectedNodes(treeState.treeData, keys).map(
		(key: string | number) => treeState.flatTreeObj[key]
	) as TsSelectedList[];

	// 回显全选
	if (rightState.selectedList.length === treeState.treeData[0].children.length) {
		rightState.selectedList = treeState.treeData;
	}
};

// 是否自动展开父节点
const Code_Top = (): any => {
	const searchValue = ref();
	const SearchTreeByInput = (treeState: TsTreeState): void => {
		let expandKeys: (string | number)[] = [treeState.treeData[0].id];
		const tempFindFlags: Array<any> = [];

		if (searchValue.value) {
			for (const key in treeState.flatTreeObj) {
				const node = treeState.flatTreeObj[key];
				if (node.name.indexOf(searchValue.value) > -1) {
					tempFindFlags.push(toRaw(node));
				}
			}
			if (tempFindFlags.length) {
				tempFindFlags.forEach((node: Record<string, any>) => {
					!expandKeys.includes(node.parentId) && expandKeys.push(node.parentId);
				});
			} else {
				expandKeys = [treeState.treeData[0].key];
			}
		}
		treeState.expandedKeys = [...expandKeys];
	};

	return { searchValue, SearchTreeByInput };
};
const { searchValue, SearchTreeByInput } = Code_Top();

// 右侧已勾选的列表
const Code_RightCard = (): Record<string, Function> => {
	const delSelectDevice = (treeInfo: TsSelectedList, ids: string[] = []): string[] => {
		ids.push(treeInfo.id);
		if (treeInfo.children && treeInfo.children.length) {
			treeInfo.children.forEach((item: TsSelectedList) => {
				ids.push(item.id);
				if (item.children && item.children.length) {
					delSelectDevice(item, ids);
				}
			});
		}
		return [...new Set(ids)];
	};

	// 单选删除
	const SingleDelete = (index: number, treeInfo: TsSelectedList): void => {
		delSelectDevice(treeInfo).forEach((item) => {
			treeState.checkedKeys.splice(
				treeState.checkedKeys.findIndex((delItem: string | number) => delItem === item),
				1
			);
		});

		rightState.selectedList.splice(index, 1);
	};
	// 全选删除(清空)
	const BatchDelete = (treeState: TsTreeState): void => {
		rightState.selectedList = [];
		rightState.selectedKeys = [];
		treeState.checkedKeys = [];
		treeState.selectedKeys = [];
	};

	return { SingleDelete, BatchDelete };
};
const { SingleDelete, BatchDelete } = Code_RightCard();

// 左侧通道Tree
const Code_LeftCard = (): any => {
	// 勾选Tree节点
	const CheckTreeNode = (checkedKeys: any[]): void => {
		formatRightSelectData(checkedKeys);
	};

	// 格式化Tree
	const formatTree = (datas: TreeProps['treeData']) => {
		if (datas) {
			for (const node of datas) {
				// 节点添加选中属性

				if (Array.isArray(node.children) && node.children.length) {
					// 给节点的父级节点添加半选属性
					formatTree(node.children);
				} else {
					node.children = [];
				}

				treeState.flatTreeObj[node.id] = node;
			}
		}
	};

	// 删除树的disabled字段
	const delDisabled = (datas: TreeProps['treeData']) => {
		if (datas) {
			for (const node of datas) {
				if (Array.isArray(node.children) && node.children.length) {
					delDisabled(node.children);
				} else {
					node.children = [];
				}
				delete node.disabled;
				console.log(node);
			}
		}
	};
	const getPermissionData = async (): Promise<void> => {
		let res = await AccountAPI.PermissionData(props.userId);
		dataId.value = res.data.id;
		treeState.checkedKeys = res.data.deviceIdList;
		formatRightSelectData(treeState.checkedKeys);
	};

	const getTreeData = async (): Promise<void> => {
		const res: TsRes = await AlgorithmConfigurationAPI.getDeviceList();
		console.log(res);
		delDisabled(res.data);
		if (Array.isArray(res.data) && res.data.length) {
			treeState.treeData = [
				{
					id: '0',
					name: '全选',
					children: [...res.data]
				}
			];
			treeState.isshowchecked = false;
			// 默认展开
			treeState.expandedKeys = ['0'];
			treeState.flatTreeObj[0] = treeState.treeData[0];
			// 遍历格式化
			await formatTree(treeState.treeData[0].children);

			await getPermissionData();
		}
	};

	return { CheckTreeNode, getTreeData };
};
const { CheckTreeNode, getTreeData } = Code_LeftCard();

const watchStop = watch(
	() => rightState.selectedKeys,

	() => {
		const newList = rightState.selectedList.map((item: Record<string, any>) => item.deviceIdAndChannelId);
		emits('update:saveData', newList);
	}
);

onMounted(async () => {
	pageLoading.value = true;
	await getTreeData();
	pageLoading.value = false;
});
onUnmounted(() => {
	watchStop();
});
</script>

<style lang="less">
.content {
	padding: 40px 32px;

	.data-type-box {
		display: flex;
		align-items: center;
		gap: 6px;
		margin-bottom: 24px;

		.tab-item {
			display: inline-block;
			height: 30px;
			padding: 0 12px;
			font-size: 14px;
			font-weight: 700;
			line-height: 30px; /* 157.143% */
			color: @text02;

			&--active {
				color: @text01;
				background: rgba(240, 246, 252, 0.1);
			}
		}
	}

	.account-data-permissions {
		display: flex;
		align-items: center;

		.ant-tree-checkbox-inner {
			border-color: @mask02 !important;
			border-radius: 3px !important;
			background-color: @mask01 !important;
		}

		.ant-tree-checkbox {
			border-radius: 3px !important;
			margin-block-start: 0 !important;
		}

		.ant-tree-checkbox-checked {
			background-color: @primary01 !important;
		}

		:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-switcher {
			position: relative;
			flex: none;
			align-self: center;
			width: 24px;
			margin: 0;
			line-height: 24px;
			text-align: center;
			cursor: pointer;
			user-select: none;
		}

		:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected,
		:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-checkbox + span.ant-tree-node-selected {
			background-color: @background01 !important;
		}

		.ant-tree-treenode {
			display: flex;
			// line-height: 20px !important;
			align-items: center !important;
		}

		.tree-node-item {
			span {
				margin-top: 2px !important;
			}
		}

		.left-tree {
			.tree-node-item {
				font-size: 12px;
				font-weight: 700;
				font-style: normal;
				// line-height: 22px !important;
				color: @text01;

				span {
					margin-top: 2px;
				}
			}
		}

		.ant-card {
			background: @background02 !important;
		}

		.ant-card-head {
			min-height: 36px !important;
			border-bottom: 1px solid @borderColor02 !important;
			background: #101a2f !important;
		}

		.ant-tree-list-holder-inner {
			margin-left: -28px;
		}

		.ant-tree-list-holder-inner > div:first-child {
			margin-left: 48px;

			.ant-tree-switcher {
				display: none;
			}
		}

		.ant-tree-switcher {
			display: block;

			svg {
				color: #f0f6fc;
			}
		}

		.ant-tree {
			background-color: transparent !important;
		}

		.ant-tree-node-selected {
			background: none !important;
		}

		.cards-item-left {
			width: 304px;
			height: 430px;
			border: 1px solid @borderColor03 !important;
			border-top-right-radius: 0;
			border-bottom-right-radius: 0;

			.cards-input-search {
				// width: 280px;
				height: 36px;
				margin-top: 8px;
				margin-bottom: 13px;
				border: 1px solid @mask02;
				border-radius: 6px;
				font-size: 14px;
				font-weight: 400;
				background: transparent !important;

				.ant-input {
					color: @text03 !important;
					background-color: transparent !important;

					&::placeholder {
						color: @text04 !important;
					}
				}

				.icon-search-line {
					font-size: 14px;
					color: @text03;
					cursor: pointer;
				}
			}

			.ant-tree {
				width: 100%;
			}

			.ant-tree-treenode {
				margin-top: 5px;
			}

			.ant-tree-treenode-checkbox-checked > .ant-tree-node-content-wrapper {
				width: 244px;
				height: 24px;
				border-radius: 2px;
				// background: #d6e2f9;
			}

			.ant-card-head {
				// height: 20px;
				border: 0;
				padding: 0;
				color: @text02;
				background: #101a2f;

				.ant-card-head-title {
					border-bottom: 1px solid @borderColor02;
					padding: 3px 12px 6px;
					font-weight: 700;
				}
			}

			.ant-card-body {
				overflow: hidden;
				overflow-y: scroll;
				width: 224px;
				width: 100%;
				height: calc(100% - 40px);
				padding: 2px 12px 12px;
				background: @background02;
			}
		}

		.ant-card-body {
			overflow: hidden;
			height: calc(100% - 40px);
			padding: 8px 8px 8px 12px;
		}

		.cards-item-right {
			width: 296px;
			height: 430px;
			border: 1px solid @borderColor02 !important;
			border-left: none !important;
			border-top-left-radius: 0;
			border-bottom-left-radius: 0;
			background: @background02;

			.card-title {
				margin-right: 5px;
				font-weight: 700;
				color: @text02;
			}

			.select-item {
				justify-content: space-between;
				display: flex;
				margin-bottom: 10px !important;
				line-height: 22px;
				color: @text01;

				.select-text {
					overflow: hidden;
					width: value;
					line-height: 22px;
					white-space: nowrap;
					text-overflow: ellipsis;
					color: @text01;
				}

				.select-del {
					.iconfont {
						font-size: 14px;
						color: @text04;
					}
				}
			}
		}
	}
}

.empty {
	color: #009cf8;
	cursor: pointer;
}
</style>
